import { defineStore } from 'pinia'
import {userStore} from "@/components/store/index.js";
import request from "@/utils/request.js";
import {ElMessage} from "element-plus";

export const messageStore = defineStore('message', {
    // 存储全局变量
    state: () => ({
        unreadAnnReceivers: [],
        allAnnReceivers: [],

        allConversations: [],
        unreadConversations: [],
        mCurrentConversation:{},
    }),

    // 计算属性
    getters: {

    },

    // 同步修改状态信息
    actions: {

        // 更新公告列表
        updateUnreadAnnReceivers() {
            this.unreadAnnReceivers = this.allAnnReceivers?.filter(ann => ann.readStatus===0)
        },
        //更新未读
        updateUnreadConversations() {
            this.unreadConversations = this.allConversations?.filter(convo => convo.isReadCon === 0)
        },


        addMessage(msg) {
            // 查找或创建对话
            let conversation = this.allConversations.find(
                convo => convo.id == msg.conversationId
            );

            if (!conversation) {
                //数据库查找新的对话；
                request.get(`/conversation/getConversationById/${msg.conversationId}`).then((resp) => {
                    if (resp.data) {
                        conversation = resp.data;
                        // 更新现有对话
                        // conversation.messages=[{}];
                        conversation.messages.push(msg);
                        conversation.latestMessage = msg;
                        conversation.unreadCount = (conversation.unreadCount || 0) + 1;
                        conversation.isReadCon = 0;
                        this.allConversations.push(conversation);
                    }
                })

            } else {
                // 更新现有对话
                conversation.messages.push(msg);
                conversation.latestMessage = msg;
                conversation.unreadCount = (conversation.unreadCount || 0) + 1;
                conversation.isReadCon = 0;

            }

            // 更新未读对话列表
            this.updateUnreadConversations();

            // 确保响应式更新
            this.allConversations = [...this.allConversations];
        },

        // 设置对话消息
        setConversationMessages(conversationId, messages) {
            const index = this.allConversations.findIndex(convo => convo.id === conversationId);
            if (index !== -1) {
                // 使用Vue.set或直接替换数组确保响应式
                this.allConversations[index].messages = [...messages];
                // 确保触发更新
                this.allConversations = [...this.allConversations];
            }
        },
        markAsRead (conversationId,userId) {
            // 后端更新，调用API标记为已读
            request.put(`/conversation/markAsRead/${conversationId}/${userId}`)
                .then(() => {
                    // Pinia更新，创建新数组，替换特定元素
                    this.allConversations = this.allConversations?.map(conversation => {
                        if (conversation.id === conversationId) {
                            return {
                                ...conversation,
                                isReadCon: 1,
                                unreadCount: 0
                            };
                        }
                        return conversation;
                    });
                    this.updateUnreadConversations();
                }).catch(error => {
                ElMessage.error('标记消息为已读失败');
            });
        },
        clearConversationAndMessages () {
            this.unreadAnnReceivers=[],
            this.allAnnReceivers=[],
            this.allConversations=[],
            this.unreadConversations=[],
            this.mCurrentConversation= {}
        }
    },

    // 持久化存储
    persist: {
        enabled: true,
        storage: localStorage,
        paths: ['allAnnReceivers', 'allConversations','unreadConversations','unreadAnnReceivers'] // 只持久化必要的数据
    }
})
